package com.kfm.dao;

import com.kfm.model.FileDO;
import com.kfm.model.FileDTO;
import com.kfm.util.DBUtil;

import java.sql.SQLException;
import java.util.List;

public class FileDao {

    private DBUtil<FileDO> dbUtil = new DBUtil();

    public int save(FileDO fileDO){
        String sql = "insert into file (name, path, url, size) values(?, ?, ?, ?)";
        try {
            return dbUtil.update(sql, fileDO.getName(), fileDO.getPath(), fileDO.getUrl(), fileDO.getSize());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


    public FileDO selectById(Integer id){
        String sql = "select * from file where id = ?";
        try {
            return dbUtil.queryOne(sql, FileDO.class, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int saveWithKey(FileDO fileDO){
        String sql = "insert into file (name, path, url, size, create_account) values(?, ?, ?, ?, ?)";
        try {
            return dbUtil.save(sql, true, fileDO.getName(), fileDO.getPath(), fileDO.getUrl(), fileDO.getSize(), fileDO.getCreateAccount());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }


    public int updateUrlById(Integer id, String url){
        String sql = "update file set url = ? where id = ?";
        try {
            return dbUtil.update(sql, url, id);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return -1;
    }

    public List<FileDO> selectAll(){
        String sql = "select * from file";
        try {
            return dbUtil.queryList(sql, FileDO.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<FileDTO> selectAllWithUsername(){
        String sql = "select file.*, a.username from file left join account a on a.id = file.create_account";
        try {
            DBUtil<FileDTO> db = new DBUtil<>();
            return db.queryList(sql, FileDTO.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
